package com.qf.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsStorageMapper;
import com.qf.pojo.DtsStorage;
import com.qf.service.DtsStorageService;
import com.qf.util.AliyunOSSUtil;
import com.qf.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;

/**
 */
@Service
public class DtsStorageServiceImpl implements DtsStorageService {

    @Autowired
    private DtsStorageMapper dtsStorageMapper;
    @Override
    public IPage<DtsStorage> selectPage(Integer page, Integer limit, String name, String key, String sort, String order) {

        QueryWrapper<DtsStorage> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(name),"name",name);
        queryWrapper.like(!StringUtils.isEmpty(key),"key",key);
        queryWrapper.orderBy(!StringUtils.isEmpty(sort),"asc".equalsIgnoreCase(order),sort);

        return dtsStorageMapper.selectPage(new Page<DtsStorage>(page,limit),queryWrapper);
    }



    //从配置文件读取数据  常量值可以提取到配置文件中 不至于硬编码问题
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName ;
    /**
     * 上传图片
     * @return
     */
    @Override
    public DtsStorage create(String originalFilename, long size, byte[] fileBytes) throws Exception{
        //1:上传阿里云
        //扩展名
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        //文件名
        String objectName = UUID.randomUUID(true).toString() + ext;
        //上传到阿里云OSS 对象存储中之后 返回文件的路径
        String url = AliyunOSSUtil.uploadImage(endpoint, accessKeyId, accessKeySecret, bucketName, objectName, fileBytes);

        //2:保存DB
        DtsStorage dtsStorage = new DtsStorage();
        dtsStorage.setKey(objectName);
        dtsStorage.setName(originalFilename);
        dtsStorage.setSize((int)size);
        dtsStorage.setAddTime(new Date());
        dtsStorage.setUpdateTime(new Date());
        dtsStorage.setType(ext);
        dtsStorage.setUrl(url);
        dtsStorage.setDeleted(false);

        dtsStorageMapper.insert(dtsStorage);

        return dtsStorage;
    }

    @Override
    public void delete(DtsStorage storage) {
        //直接删除
        dtsStorageMapper.deleteById(storage);

    }


}
